package com.kehao.leetcode.basic.array;


import org.junit.Test;

import java.util.Arrays;

/**
 *
 * 移动零
 * https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2ba4i/
 *
 * 给定一个数组 nums，编写一个函数将所有 0 移动到数组的末尾，同时保持非零元素的相对顺序。
 *
 * 示例:
 *
 * 输入: [0,1,0,3,12]
 * 输出: [1,3,12,0,0]
 * 说明:
 *
 * 必须在原数组上操作，不能拷贝额外的数组。
 * 尽量减少操作次数。
 *
 *
 */
public class ArraySolution8 {

    public void moveZeroes(int[] nums) {
        int zero_pos = 0;
        int normal_pos = 0;
        while (zero_pos<nums.length&&nums[zero_pos]!=0){
            zero_pos++;
        }
        while (normal_pos<nums.length&&nums[normal_pos]==0){
            normal_pos++;
        }
        while (normal_pos<nums.length&&zero_pos<nums.length){
            if(zero_pos<normal_pos){
                int temp = nums[zero_pos];
                nums[zero_pos] = nums[normal_pos];
                nums[normal_pos] = temp;
                while (nums[zero_pos]!=0){
                    zero_pos++;
                }
            }
            normal_pos++;
        }
    }

    @Test
    public void myTest01(){
        int[] nums = {0,1,0,3,12};
        moveZeroes(nums);
        Arrays.stream(nums).forEach(i-> System.out.print(i+" "));
        System.out.println();
    }

    @Test
    public void myTest02(){
        int[] nums = {0};
        moveZeroes(nums);
        Arrays.stream(nums).forEach(i-> System.out.print(i+" "));
        System.out.println();
    }

    @Test
    public void myTest03(){
        int[] nums = {1};
        moveZeroes(nums);
        Arrays.stream(nums).forEach(i-> System.out.print(i+" "));
        System.out.println();
    }

    @Test
    public void myTest04(){
        int[] nums = {1,0};
        moveZeroes(nums);
        Arrays.stream(nums).forEach(i-> System.out.print(i+" "));
        System.out.println();
    }
}
